import JSONAPISerializer from "json-api-serializer"
import request from "../../utils/request";
import flarum from "../../flarum";
import {urlEncode} from "../../utils/tools";

export class Posts {
    constructor() {
        const that = this
        that.serializer = new JSONAPISerializer()
        that.serializer.register("posts", {
            id: "id",
            relationships: {
                users: {
                    type: "users"
                },
                discussion: {
                    type: "discussion"
                },
                posts: {
                    type: "posts"
                }
            },
            topLevelMeta: function(data, extraData) {
                return {
                    count: extraData.count,
                    total: data.length
                };
            }
        })

        that.serializer.register('users', {
            type: "users",
            id: "id"
        })

        that.serializer.register('tags', {
            type: "tags",
            id: "id"
        })

        that.serializer.register('posts', {
            type: "posts",
            id: "id"
        })

        that.serializer.register('discussions', {
            type: "discussions",
            id: "id"
        })
    }


    /**
     * 获取API地址
     * @returns {string}
     * @param ids
     * @param author
     * @param type
     * @param offset
     * @param sort
     */
    getApi(ids = "",
           author = "",
           type = "comment",
           offset = 0,
           sort = "-created") {
        let url = `${flarum.api}/posts?`

        if(ids !== "") {
            url = `${url}&filter[id]=${urlEncode(ids)}`
        }

        if(author !== "") {
            url = `${url}&filter[author]=${urlEncode(author)}&filter[type]=${urlEncode(type)}`
        }

        if(sort !== "") {
            url = `${url}&sort=${sort}`
        }

        return url
    }

    /**
     * 执行列表
     * @param params
     * @param func
     */
    execute(params = {}, func) {
        const that = this
        const url = that.getApi(params.ids, params.author,
            params.type, params.offset, params.sort)
        request.get(url).then(res => {
            that.data = res
            that.viewdata = that.serializer.deserialize("posts", res)
            func(that.data, that.viewdata)
        }).catch(res => {})
    }
}